<?php

namespace App\Models\Admin\User;

class UserModel extends BaseUserModel
{

    protected $table = 'user';

    const USER_LOGIN_CACHE_FIELDS = [
        'id', 'uuid', 'username', 'nickname', 'side_mode', 'header_img', 'base_color', 'active_color', 'authority_id', 'phone', 'email', 'enable',
    ];

    const ENABLE_NORMAL = 1; // 状态-正常
    const ENABLE_FREEZE = 2; // 状态-冻结

    /**
     * 通过用户名查询用户信息
     *
     * @param string $username 用户名
     * @param array  $fields   查询字段
     * @return mixed
     */
    public function getItemByUsername(string $username, array $fields = self::QUERY_DEFAULT_FIELDS)
    {
        return $this->select($fields)
            ->where('username', $username)
            ->where('deleted', self::DELETED_NO)
            ->first();
    }

    /**
     * 根据角色id获取数据
     *
     * @param int   $authorityId
     * @param array $fields
     * @return array
     */
    public function getItemByAuthorityId(int $authorityId, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $result = $this->select($fields)
            ->where('authority_id', $authorityId)
            ->where('deleted', self::DELETED_NO)
            ->first();
        return $result ? $result->toArray() : [];
    }

    /**
     * 获取总条数
     *
     * @param array $params
     * @return int
     */
    public function getTotal(array $params): int
    {
        $query = $this->where('deleted', self::DELETED_NO);

        if (!empty($params['keyword'])) {
            $query = $query->where('nickname', "%{$params['keyword']}%");
        }
        return $query->count();
    }

    /**
     * 获取列表
     *
     * @param array $params
     * @param array $fields
     * @return array
     */
    public function getList(array $params = [], array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $query = $this->select($fields)
            ->where('deleted', self::DELETED_NO);

        if (!empty($params['keyword'])) {
            $query = $query->where('nickname', "%{$params['keyword']}%");
        }

        return $query->get()
            ->toArray();
    }

}
